
import { ColumnInfo } from '../common/bean/ColumnInfo';
import { Constants } from '../common/Constants';
import { Log } from '../common/Log';
/**
 * SQL语句工具类
 */
export class TableUtil {
  /**
   * 生成创建表的SQL语句
   * @param tableName 表名称
   * @param columns 列信息
   * @returns 返回SQL语句
   */
  static createTableSql(tableName: string, columns: Array<ColumnInfo>): string {
    let sql = `create table if not exists ${tableName}(`;
    for (let column of columns) {
      sql = sql.concat(`${column.name} ${column.type}`);
      sql = sql.concat(`${(column.length && column.length > 0) ? column.length : ''}`);
      sql = sql.concat(`${column.primary ? ' primary key' : ''}`);
      sql = sql.concat(`${column.autoincrement ? ' autoincrement' : ''}`);
      sql = sql.concat(`${column.nullable ? '' : ' not null'}`);
      sql = sql.concat(', ');
    }
    sql = `${sql.substring(0, sql.length - 2)}`;
    Log.info(Constants.LOG_TAG_NAME, `Create ${tableName} table SQL statement: '${sql}'`);
    return sql;
  }
  /**
   * 生成为表添加列的SQL语句
   * @param tableName 表名称
   * @param column  新增列信息
   * @returns
   */
  static addTableColumnSql(tableName: string, column: ColumnInfo): string {
    let sql = `alter table ${tableName} add`;
    sql = sql.concat(`${column.name} ${column.type}`);
    sql = sql.concat(`${(column.length && column.length > 0) ? column.length : ''}`);
    Log.info(Constants.LOG_TAG_NAME, `SQL statement to add column to ${tableName}: '${sql}'`);
    return sql;
  }
  /**
   * 根据表名称删除表
   * @param tableName
   */
  static deleteTableSql(tableName: string) {
    return `drop table if exists ${tableName}`;
  }
}